<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/11/23
 * Time: 9:58
 */

namespace app\admin\controller;


use think\Db;

class Rbac extends Base
{
    const TABLE_ROLE = 'rbac_role';
    const TABLE_NODE = 'rbac_node';
    const TABLE_ROLE_ADMIN = 'rbac_role_admin';
    const TABLE_ACCESS = 'rbac_access';
    const TABLE_ADMIN = 'admin';
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 用户组列表
     */
    public function role_list()
    {
        $data = Db::name(self::TABLE_ROLE)->select();
        $this->assign('data',$data);
        return $this->fetch();
    }

    /**
     * 新添用户组
     */
    public function ajax_add_role()
    {
        $data['name'] = input('name');
        $data['remark'] = input('description');
        $data['status'] = 1;
        $data['addtime'] = $data['modtime'] = time();
        if($data['name'] == ''){
            echo api_return(0,'用户组名称不能为空');
            exit;
        }
        $a = Db::name(self::TABLE_ROLE)->where('name',$data['name'])->find();
        if($a){
            echo api_return(0,'该用户组名称已存在');
            exit;
        }
        $b = Db::name(self::TABLE_ROLE)->insert($data);
        if($b){
            echo api_return(1,'添加成功');
        }else{
            echo api_return(0,'添加失败');
        }
    }

    /**
     * 列表页修改
     */
    public function ajax_update_role()
    {
        $field = input('field');
        $value = input('value');
        $id = input('id');
        $data = null;
        if($field == 'name'){
            if($value == ''){
                echo api_return(0,'用户组名称不能为空');
                exit;
            }
            if(unique_update_value($value,$id,self::TABLE_ROLE,'name','id')){
                echo api_return(0,'该用户组名称已存在');
                exit;
            }
            $data['name'] = $value;
        }
        if($field == 'remark'){
            $data[$field] = $value;
        }
        if($data){
            $data['modtime'] = time();
            $a = Db::name(self::TABLE_ROLE)->where('id',$id)->update($data);
            if($a){
                echo api_return(1,'修改成功');
                exit;
            }else{
                echo api_return(0,'修改失败');
                exit;
            }
        }else{
            echo api_return(0,'不支持的修改字段');
        }
    }

    /**
     * 删除
     */
    public function ajax_del_role()
    {
        $id = input('id');
        $a = Db::name(self::TABLE_ROLE)->where('id',$id)->delete();
        if($a){
            echo api_return(1,'删除成功');
        }else{
            echo api_return(0,'删除失败');
        }
    }

    /**
     * 权限列表
     */
    public function node_list()
    {
        $node = $this->get_node_list();
//        dump($node3);
        $this->assign('data',json_encode($node));

        return $this->fetch();
    }

    /**
     * @param $data
     * @return mixed
     * bootstrap-tree 加tags
     */
    public function node_tags($data)
    {
        foreach ($data as $k=>$v)
        {
            switch ($v['level']){
                case 1:
                    $data[$k]['tags'][] = '一级菜单';
                    break;
                case 2:
                    $data[$k]['tags'][] = '二级菜单';
                    break;
                case 3:
                    $data[$k]['tags'][] = '三级菜单';
                    break;
                case 4:
                    $data[$k]['tags'][] = '仅权限';
            }
            if($v['controller'] || $v['action']){
                $data[$k]['tags'][] = $v['controller'].'/'.$v['action'];
            }
            if(isset($v['enable']) && $v['enable']){
                $data[$k]['state']['checked'] = true;
            }else{
                $data[$k]['state']['checked'] = false;
            }
        }
        return $data;
    }
    /**
     * @param $p_data 父级权限
     * @param $data 子级权限
     * @return mixed
     * 树级菜单权限
     */
    public function tree_node($p_data,$data)
    {
        foreach ($p_data as $key=>$value)
        {
            foreach ($data as $k=>$v)
            {
                if($value['id'] == $v['pid']){
                    $p_data[$key]['nodes'][] = $v;
                }
            }
        }
        return $p_data;
    }


    /**
     * @return mixed
     * 添加权限节点
     */
    public function add_node()
    {
        if(!request()->isPost()){
            $data = Db::name(self::TABLE_NODE)->where('level',1)->order('sort desc')->select();
            $this->assign('data',$data);
            return $this->fetch();
        }else{
//            dump(input());exit;
            $data['name'] = input('name');
            $data['controller'] = input('controller');
            $data['action'] = input('action');
            $data['level'] = input('level');
            $data['sort'] = input('sort');

            $pid1 = input('pid_1');
            $pid2 = input('pid_2');

            $data['pid'] = $pid2?:$pid1?:0;
            $data['addtime'] = $data['modtime'] = time();
            $a = Db::name(self::TABLE_NODE)->insert($data);
            if($a){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }
    }

    /**
     * 修改权限
     */
    public function update_node()
    {
        $id = input('id');
        $node = Db::name(self::TABLE_NODE)->where('id',$id)->find();
        if(!request()->isPost()){
            $data2 = $data3 = null;
            $data1 = Db::name(self::TABLE_NODE)->where('level',1)->order('sort desc')->select();
            $level = 0;
            if($node['level'] > 1){
                //父级权限
                $pnode = Db::name(self::TABLE_NODE)->where('id',$node['pid'])->find();
                $level = $pnode['level'];
                //找出父级权限的同辈
                switch ($level){
                    case 2:
                        $data2 = Db::name(self::TABLE_NODE)->where('pid',$pnode['pid'])->order('sort desc')->select();
                        break;
                    case 3:
                        $data3 = Db::name(self::TABLE_NODE)->where('pid',$pnode['pid'])->order('sort desc')->select();
                }

            }

            $this->assign('data1',$data1);
            $this->assign('data2',$data2);
            $this->assign('data3',$data3);
            $this->assign('p_level',$level);
            $this->assign('node',$node);
            return $this->fetch();
        }else{
            $data['name'] = input('name');
            $data['controller'] = input('controller');
            $data['action'] = input('action');
            $data['level'] = input('level');
            $data['sort'] = input('sort');

            $pid1 = input('pid_1');
            $pid2 = input('pid_2');

            $data['pid'] = $pid2?:$pid1?:0;
            $data['modtime'] = time();
            $a = Db::name(self::TABLE_NODE)->where('id',$id)->update($data);
            if($a){
                $this->success('保存成功');
            }else{
                $this->error('保存失败');
            }
        }
    }

    /**
     * 删除权限节点
     */
    public function access_ajax_del_node()
    {
        $id = input('id');
        $child_node = Db::name(self::TABLE_NODE)->where('pid',$id)->find();
        if($child_node){
            echo api_return(0,'请先删除子权限');
            exit;
        }
        $a = Db::name(self::TABLE_NODE)->where('id',$id)->delete();
        if($a){
            echo api_return(1,'删除成功');
        }else{
            echo api_return(0,'删除失败');
        }
    }

    /**
     * 获取父级权限菜单
     */
    public function ajax_get_node()
    {
        $id = input('id');
        $data = Db::name(self::TABLE_NODE)->where('pid',$id)->order('sort desc')->select();
        if($data){
            echo api_return(1,'查询成功',$data);
        }else{
            echo api_return(0,'尚未配置');
        }
    }

    /**
     * 用户组配置权限
     */
    public function set_access()
    {
        $id = input('id');
        $role = Db::name(self::TABLE_ROLE)->where('id',$id)->find();
        if (!$role){
            $this->error('该用户组不存在');
        }
        $node = $this->get_access_node_list($id);
        $this->assign('data',json_encode($node));
        $this->assign('role',$role);
        return $this->fetch();
    }

    /**
     * 获取权限列表
     */
    public function get_node_list()
    {
        $node1 = $this->get_node(1);
        $node2 = $this->get_node(2);
        $node3 = $this->get_node(3);
//        $node4 = $this->get_node(4);

        $node1 = $this->node_tags($node1);
        $node2 = $this->node_tags($node2);
        $node3 = $this->node_tags($node3);
//        $node4 = $this->node_tags($node4);

//        $node3 = $this->tree_node($node3,$node4);
        $node2 = $this->tree_node($node2,$node3);
//        $node2 = $this->tree_node($node2,$node4);
        $node1 = $this->tree_node($node1,$node2);

        return $node1;
    }

    /**
     * 获取权限列表
     */
    public function get_access_node_list($role_id)
    {
        $node1 = $this->get_node(1,false);
        $access1 = $this->get_access_node(1,$role_id);
        $node1 = $this->unset_unique_node($node1,$access1);

        $node2 = $this->get_node(2,false);
        $access2 = $this->get_access_node(2,$role_id);
        $node2 = $this->unset_unique_node($node2,$access2);

        $node3 = $this->get_node(3,false);
        $access3 = $this->get_access_node(3,$role_id);
        $node3 = $this->unset_unique_node($node3,$access3);

//        $node4 = $this->get_node(4);
//        $access4 = $this->get_access_node(4,$role_id);
//        $node4 = $this->unset_unique_node($node4,$access4);

        $node1 = $this->node_tags($node1);
        $node2 = $this->node_tags($node2);
        $node3 = $this->node_tags($node3);
//        $node4 = $this->node_tags($node4);

//        $node3 = $this->tree_node($node3,$node4);
        $node2 = $this->tree_node($node2,$node3);
//        $node2 = $this->tree_node($node2,$node4);
        $node1 = $this->tree_node($node1,$node2);

        return $node1;
    }

    /**
     * @param $level权限分级
     * @return false|mixed|\PDOStatement|string|\think\Collection
     * 按分级获取权限
     */
    private function get_node($level,$all = true)
    {
        if(!$all){
            $where['display'] = 1;
        }else{
            $where = '1=1';
        }
        $node = Db::name(self::TABLE_NODE)
            ->where('level',$level)
            ->where($where)
            ->field('id,name as text,level,pid,controller,action')
            ->order('sort desc')
            ->select();
        return $node;
    }

    /**
     * @param $level
     * @param $role_id
     * @return false|mixed|\PDOStatement|string|\think\Collection
     * 按分级获取某个用户组的权限
     */
    private function get_access_node($level,$role_id)
    {
        $node = Db::name(self::TABLE_NODE)
            ->alias('a')
            ->join('rbac_access b','b.node_id=a.id')
            ->where('a.level',$level)
            ->where('b.role_id',$role_id)
            ->field('a.id as id,a.name as text,a.level,pid as pid,a.controller,a.action,b.id as enable')
            ->order('a.sort desc')
            ->select();
        return $node;
    }

    /**
     * 去掉重复的数组
     */
    private function unset_unique_node($node,$access)
    {
        foreach ($node as $key=>$value)
        {
            foreach ($access as $k=>$v)
            {
                if($value['id'] == $v['id']){
                    $node[$key] = $v;
                }
            }
        }
        return $node;
    }

    /**
     * 保存权限
     */
    public function ajax_save_access()
    {
        $param = input();
        $id = input('id');
        $node = $param['node'];
        $role = Db::name(self::TABLE_ROLE)->where('id',$id)->find();
        if (!$role){
            echo api_return(0,'该用户组不存在');
            exit;
        }

        Db::name(self::TABLE_ACCESS)->where('role_id',$id)->delete();
        if($node){
            foreach ($node as $key=>$value)
            {
                $a['role_id'] = $id;
                $a['node_id'] = $value;
                $data[] = $a;
            }
            $a = Db::name(self::TABLE_ACCESS)->insertAll($data);
            if($a){
                echo api_return(1,'保存成功');
            }else{
                echo api_return(0,'保存失败');
            }
        }else{
            echo api_return(1,'保存成功');
        }

    }

}